package com.jy.appmarket.screenlock.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;

import com.jy.appmarket.R;
import com.jy.appmarket.utils.LogUtil;

import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-3-24
 * @version 1.0
 */
public class XiaomiUtils {
	private static final String TAG = XiaomiUtils.class.getName();
    public static final String MUIU_V5 = "V5";
    public static final String MUIU_V6 = "V6";
    public static final String MUIU_V7 = "V7";

	@SuppressLint("DefaultLocale")
	public static boolean xiaomiSystem(Context context) {
		boolean isXiaomi = false;
		if ("xiaomi".equalsIgnoreCase(Build.MANUFACTURER)) {
			isXiaomi = true;
			Intent localIntent = new Intent(
					"miui.intent.action.APP_PERM_EDITOR");
			localIntent.setClassName("com.android.settings",
					"com.miui.securitycenter.permission.AppPermissionsEditor");
			if (!(context.getPackageManager()
					.queryIntentActivities(localIntent, 1).size() > 0)) {
				boolean bool2 = "miui".equalsIgnoreCase(Build.ID);
				if ("xiaomi".equalsIgnoreCase(Build.BRAND)) {
					bool2 = isXiaomi;
				}
				if (Build.MODEL != null) {
					String str = Build.MODEL.toLowerCase();
					if (str.contains("xiaomi")) {
						bool2 = isXiaomi;
					}
					if (str.contains("miui")) {
						bool2 = isXiaomi;

					}
				}
				isXiaomi = bool2;
			}
		}
		return isXiaomi;
	}
    public static boolean isMIUI(Context context) {
        String manufacturer = android.os.Build.MANUFACTURER;
        return /*"Xiaomi".equals(manufacturer) ||*/ !TextUtils.isEmpty(getSystemProperty());
    }

    public static boolean isMeizu(Context context) {
        String manufacturer = android.os.Build.MANUFACTURER;
        return "Meizu".equals(manufacturer);
    }

	public static void openFloatWindow(Context context, String paramString) {
		try {
			if (miUIV6(context)) {
				Intent localIntent = new Intent(
						"miui.intent.action.APP_PERM_EDITOR");
				localIntent
						.setComponent(new ComponentName(
								"com.miui.securitycenter",
								"com.miui.permcenter.permissions.AppPermissionsEditorActivity"));
				localIntent.putExtra("extra_pkgname", context.getPackageName());
				if (isIntentAvailable(context,localIntent)) {
					context.startActivity(localIntent);
				}
			} else {
				Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS",
						Uri.parse("package:" + paramString));
				if (isIntentAvailable(context,intent)) {
					context.startActivity(intent);
				}
			}
		} catch (Exception localException) {
			localException.printStackTrace();
		}
	}

	/**
	 * 判断是否有可以接受的Activity
	 * 
	 * @param context
	 * @param action
	 * @return
	 */
	public static boolean isIntentAvailable(Context context, Intent intent) {
		if (intent == null)
			return false;
		return context.getPackageManager().queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES).size() > 0;
	}

	public static boolean miUIV6(Context context) {
		boolean bool = false;
		if (xiaomiSystem(context) && ("V6".equalsIgnoreCase(getSystemProperty()))) {
			bool = true;
		}
		return bool;
	}

    public static String getSystemProperty() {
        String line = "";
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + "ro.miui.ui.version.name");
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return line;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return line;
    }
    public static void setAllowFolatWindow(Context mContent, String version) {
        try {
            if (version.equals(MUIU_V5)) {
                Uri packageURI = Uri.parse("package:" + mContent.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                mContent.startActivity(intent);
            } else if (version.equals(MUIU_V6)) {
                Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
                i.setClassName("com.miui.securitycenter",
                        "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                i.putExtra("extra_pkgname", mContent.getPackageName());
                mContent.startActivity(i);
            } else if (version.equals(MUIU_V7)) {
            	 Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
                 i.setClassName("com.miui.securitycenter",
                         "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                 i.putExtra("extra_pkgname", mContent.getPackageName());
                 mContent.startActivity(i);
            }
        } catch (Exception e) {
            Toast.makeText(mContent, R.string.error, Toast.LENGTH_SHORT).show();
        }
    }
    public static boolean setTrust(Context mContent, String version) {
        try {
            if (version.equals(MUIU_V5)) {
                PackageManager pm = mContent.getPackageManager();
                PackageInfo info = null;
                info = pm.getPackageInfo(mContent.getPackageName(), 0);

                Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
                i.setClassName("com.android.settings",
                        "com.miui.securitycenter.permission.AppPermissionsEditor");
                i.putExtra("extra_package_uid", info.applicationInfo.uid);
//                i.putExtra("extra_pkgname", mContent.getPackageName());
                mContent.startActivity(i);
            } else if (version.equals(MUIU_V6)) {
                Intent i = new Intent();
                i.setClassName("com.miui.securitycenter", "com.miui.securitycenter.MainActivity");
                mContent.startActivity(i);
            } else if (version.equals(MUIU_V7)) {
                Intent i = new Intent();
                i.setClassName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
                mContent.startActivity(i);
            }
            return true;
        } catch (Exception e) {
            Toast.makeText(mContent, "系统版本过低，无法操作", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    public static void closeSystemLocker(Context context, boolean isMIUI) {
        try {
            if (isMIUI) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                context.startActivity(intent);
            } else {
                Intent intent = new Intent("/");
                ComponentName cm = new ComponentName("com.android.settings",
                        "com.android.settings.ChooseLockGeneric");
                intent.setComponent(cm);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 判断MIUI的悬浮窗权限
     * @param context
     * @return
     */
    public static boolean isFloatWindowOpAllowed(Context context) {
        final int version = Build.VERSION.SDK_INT;
        
        if (version >= Build.VERSION_CODES.KITKAT) {
            return checkOp(context, 24);
        } else {
            return (context.getApplicationInfo().flags & 1 << 27) == 1;
        }
    }
    
    public static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        boolean permission = false; 
        if (version >= Build.VERSION_CODES.KITKAT) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
            	 Class<?>[] paramTypes = new Class<?>[]{int.class, int.class, String.class};
            	 Object[] params = new Object[]{op, Binder.getCallingUid(), context.getPackageName()};
            	 Integer result = (Integer)invokeMethod(manager, "checkOp", paramTypes, params);
                if (result.intValue() == AppOpsManager.MODE_ALLOWED) {
                	permission = true;
                }
            } catch (Exception e) {
            	LogUtil.e(TAG, e.getMessage());
            }
        } else {
            LogUtil.e(TAG, "Below API 19 cannot invoke!");
        }
        return permission;
    }
    
    public static Object invokeMethod(Object obj, String methodName,
            Class<?>[] paramTypes, Object[] params) throws Exception {

        Object value = null;
        Class<?> cls = obj.getClass();

        // 注意不要用getMethod(),因为getMethod()返回的都是public方法
        Method method = cls.getDeclaredMethod(methodName, paramTypes);

        method.setAccessible(true);// 抑制Java的访问控制检查

        value = method.invoke(obj, params);
        return value;
    }
}
